package org.zebra.web.advice.crypto;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdviceAdapter;
import org.zebra.common.crypto.CryptoProvider;
import org.zebra.common.exception.ResultException;
import org.zebra.common.exception.StatusCode;
import org.zebra.web.annotation.crypto.ApiCrypto;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * 请求解密处理器
 *
 * @author zhanghongbin
 */
@Slf4j
@ControllerAdvice
public class ApiDecryptRequestBodyAdvice extends RequestBodyAdviceAdapter {

    private CryptoProvider cryptoProvider;

    public ApiDecryptRequestBodyAdvice(CryptoProvider cryptoProvider) {
        this.cryptoProvider = cryptoProvider;
    }

    @Override
    public boolean supports(
            MethodParameter methodParameter, Type targetType, Class<? extends HttpMessageConverter<?>> converterType) {
        ApiCrypto apiCrypto = methodParameter.getMethodAnnotation(ApiCrypto.class);
        return apiCrypto != null ? apiCrypto.request() : false;
    }

    @Override
    public HttpInputMessage beforeBodyRead(
            HttpInputMessage inputMessage,
            MethodParameter parameter,
            Type targetType,
            Class<? extends HttpMessageConverter<?>> converterType)
            throws IOException {
        String result;
        try {
            result = cryptoProvider.decrypt(StreamUtils.copyToString(inputMessage.getBody(), Charset.defaultCharset()));
            log.info("【内容解密】decryptStr={}", result);
        } catch (Exception e) {
            throw new ResultException(StatusCode.ENCRYPT_FAILED.getCode(), StatusCode.ENCRYPT_FAILED.getMsg());
        }
        return new HttpInputMessage() {
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(result.getBytes());
            }

            @Override
            public HttpHeaders getHeaders() {
                return inputMessage.getHeaders();
            }
        };
    }
}
